package org.dromara.web.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.enums.UserStatus;
import org.dromara.common.core.exception.user.UserException;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.web.service.SysLoginService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 首页
 *
 * @author Lion Li
 */
@SaIgnore
@RequiredArgsConstructor
@RestController
public class IndexController {

    /**
     * 系统基础配置
     */
    private final SysLoginService loginService;
    private final SysUserMapper userMapper;

    /**
     * 访问首页，提示语
     */
    @GetMapping("/")
    public String index(Long userId) {

        if ("prod".equals(SpringUtils.getActiveProfile()) || ObjectUtil.isEmpty(userId)) {
            return StringUtils.format("欢迎使用后台管理框架，请通过前端地址访问。");
        }

        SysUserVo user = loadUserByUserId("000000",userId);
        // 此处可根据登录用户的数据不同 自行创建 loginUser
        SaLoginModel model = new SaLoginModel();
        model.setDevice("pc");
        model.setExtra(LoginHelper.CLIENT_KEY, "e5cd7e4891bf95d1d19206ce24a7b32e");

        // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
        // 例如: 后台用户30分钟过期 app用户1天过期
        model.setTimeout(Integer.MAX_VALUE);
        model.setActiveTimeout(Integer.MAX_VALUE);

        LoginUser loginUser = loginService.buildLoginUser(user);

        // 生成token
        LoginHelper.login(loginUser, model);
        return StpUtil.getTokenValue();
    }

    public SysUserVo loadUserByUserId(String tenantId, Long userId) {
        return TenantHelper.dynamic(tenantId, () -> {
            SysUser user = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .select(SysUser::getUserId, SysUser::getStatus)
                .eq(SysUser::getUserId, userId));
            if (ObjectUtil.isNull(user)) {
                throw new UserException("user.not.exists", userId);
            } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
                throw new UserException("user.blocked", userId);
            }
            return userMapper.selectVoById(userId);
        });
    }
}
